package org.csu.onlineedubackend.controller;

import org.csu.onlineedubackend.dto.CourseListDTO;
import org.csu.onlineedubackend.dto.PageResponseDTO;
import org.csu.onlineedubackend.dto.StudentListDTO;
import org.csu.onlineedubackend.dto.TeacherListDTO;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.CourseService;
import org.csu.onlineedubackend.service.LessonService;
import org.csu.onlineedubackend.service.StudentCourseService;
import org.csu.onlineedubackend.service.UserService;
import org.csu.onlineedubackend.entity.Log;
import org.csu.onlineedubackend.mapper.LogMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 管理员控制器
 */
@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private StudentCourseService studentCourseService;

    @Autowired
    private LessonService lessonService;

    @Autowired
    private LogMapper logMapper;

    /**
     * 获取学生统计数据
     */
    @GetMapping("/student-stats")
    public CommonResponse<Map<String, Object>> getStudentStats() {
        try {
            Map<String, Object> stats = userService.getStudentStats();
            return CommonResponse.createForSuccess(
                    200,
                    "获取学生统计数据成功",
                    stats
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                   500,
                    "获取学生统计数据失败: " + e.getMessage()
            );
        }
    }

    /**
     * 获取教师统计数据
     */
    @GetMapping("/teacher-stats")
    public CommonResponse<Map<String, Object>> getTeacherStats() {
        try {
            Map<String, Object> stats = userService.getTeacherStats();
            return CommonResponse.createForSuccess(
                    200,
                    "获取教师统计数据成功",
                    stats
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                    500,
                    "获取教师统计数据失败: " + e.getMessage()
            );
        }
    }

    /**
     * 获取视频统计数据
     */
    @GetMapping("/video-stats")
    public CommonResponse<Map<String, Object>> getLessonStats() {
        try {
            Map<String, Object> stats = lessonService.getLessonStats();
            return CommonResponse.createForSuccess(
                    200,
                    "获取视频统计数据成功",
                    stats
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                    500,
                    "获取视频统计数据失败: " + e.getMessage()
            );
        }
    }

    
    /**
     * 获取课程统计数据
     */
    @GetMapping("/course-stats")
    public CommonResponse<Map<String, Object>> getCourseStats() {
        try {
            Map<String, Object> stats = courseService.getCourseCountByStatus();
            return CommonResponse.createForSuccess(
                    200,
                    "获取课程统计数据成功",
                    stats
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                   500,
                    "获取课程统计数据失败: " + e.getMessage()
            );
        }
    }

    /**
     * 获取每月活跃学生数（月活）
     */
    @GetMapping("/statistics/monthly-active-students")
    public CommonResponse<List<Map<String, Object>>> getMonthlyActiveStudents() {
        List<Map<String, Object>> data = studentCourseService.getMonthlyActiveStudents();
        return CommonResponse.createForSuccess(200, "获取月活跃学生成功", data);
    }

    /**
     * 获取每月活跃学生数（月活）
     */
    @GetMapping("/statistics/day-active-students")
    public CommonResponse<List<Map<String, Object>>> getDayActiveStudents() {
        List<Map<String, Object>> data = studentCourseService.getDailyActiveStudents();
        return CommonResponse.createForSuccess(200, "获取日活跃学生成功", data);
    }

    /**
     * 获取每月注册学生数
     */
    @GetMapping("/statistics/monthly-registered-students")
    public CommonResponse<List<Map<String, Object>>> getMonthlyRegisteredStudents() {
        List<Map<String, Object>> data = userService.getMonthlyRegisteredStudents();
        return CommonResponse.createForSuccess(200, "获取月注册学生成功", data);
    }


    /**
     * 分页获取学生列表
     */
    @GetMapping("/students")
    public CommonResponse<PageResponseDTO<StudentListDTO>> getStudentList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String sort) {
        return CommonResponse.createForSuccess(200, "获取学生列表成功", userService.getStudentPage(page, size, sort));
    }

    @GetMapping("/top-students")
    public List<StudentListDTO> getTopStudents(
            @RequestParam(defaultValue = "studyTime") String sort,
            @RequestParam(defaultValue = "3") int limit
    ) {
        return userService.getTopStudents(sort, limit);
    }

    /**
     * 分页获取教师列表
     */
    @GetMapping("/teachers")
    public CommonResponse<PageResponseDTO<TeacherListDTO>> getTeacherList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        return CommonResponse.createForSuccess(200, "获取教师列表成功", userService.getTeacherPage(page, size));
    }

    /**
     * 分页获取课程列表（course.vue使用 - 显示状态为1（上架）,2（下架）的课程）
     */
    @GetMapping("/courses")
    public CommonResponse<PageResponseDTO<CourseListDTO>> getCourseList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        return CommonResponse.createForSuccess(200, "获取课程列表成功", courseService.getCoursePage(page, size));
    }

    /**
     * 分页获取待审批课程列表（notice.vue使用 - 显示状态为1（上架,2（下架）,3（要核审的）4（拒绝）的课程）
     */
    @GetMapping("/courses/approval")
    public CommonResponse<PageResponseDTO<CourseListDTO>> getApprovalCourseList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status) {
        return CommonResponse.createForSuccess(200, "获取待审批课程列表成功", courseService.getApprovalCoursePage(page, size, status));
    }

    /**
     * 分页获取热门课程列表（按订阅数排序）
     */
    @GetMapping("/courses/ranking")
    public CommonResponse<PageResponseDTO<CourseListDTO>> getCourseRankingList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "subscriber_count") String orderBy,
            @RequestParam(defaultValue = "desc") String orderType) {
        return CommonResponse.createForSuccess(200, "获取热门课程列表成功", courseService.getCourseRankingPage(page, size, orderBy, orderType));
    }

    /**
     * 审批课程 - 通过
     */
    @PutMapping("/courses/{courseId}/approve")
    public CommonResponse<Boolean> approveCourse(@PathVariable Integer courseId) {
        try {
            boolean success = courseService.approveCourse(courseId);
            if (success) {
                return CommonResponse.createForSuccess(200, "课程审批通过成功", true);
            } else {
                return CommonResponse.createForError(400, "课程审批失败");
            }
        } catch (Exception e) {
            return CommonResponse.createForError(500, "课程审批失败: " + e.getMessage());
        }
    }

    /**
     * 审批课程 - 拒绝
     */
    @PutMapping("/courses/{courseId}/reject")
    public CommonResponse<Boolean> rejectCourse(@PathVariable Integer courseId) {
        try {
            boolean success = courseService.rejectCourse(courseId);
            if (success) {
                return CommonResponse.createForSuccess(200, "课程拒绝成功", true);
            } else {
                return CommonResponse.createForError(400, "课程拒绝失败");
            }
        } catch (Exception e) {
            return CommonResponse.createForError(500, "课程拒绝失败: " + e.getMessage());
        }
    }

    /**
     * 分页获取日志列表
     * type: exception, system, security, course, student
     */
    @GetMapping("/logs")
    public CommonResponse<Map<String, Object>> getLogs(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String type) {
        QueryWrapper<Log> wrapper = new QueryWrapper<>();
        if (type != null) {
            switch (type) {
                case "system":
                    wrapper.eq("log_type", "API");
                    break;
                case "exception":
                    wrapper.eq("level", "ERROR");
                    break;
                case "security":
                    wrapper.eq("level", "WARN");
                    break;
                case "course":
                    wrapper.eq("module", "课程操作");
                    break;
                case "student":
                    wrapper.in("action", new String[]{"LOGIN", "LOGOUT", "COMMENT", "LIKE", "UNLIKE", "SUBSCRIBE", "UNSUBSCRIBE", "PROGRESS_UPDATE"});
                    break;
            }
        }
        wrapper.orderByDesc("created_at");
        Page<Log> logPage = logMapper.selectPage(new Page<>(page, size), wrapper);
        Map<String, Object> result = new java.util.HashMap<>();
        result.put("records", logPage.getRecords());
        result.put("total", logPage.getTotal());
        result.put("pages", logPage.getPages());
        result.put("current", logPage.getCurrent());
        return CommonResponse.createForSuccess(200, "获取日志成功", result);
    }

} 